package com.amt.olcacon.utils;

import org.openlca.core.model.descriptors.ImpactDescriptor;
import org.openlca.core.results.LcaResult;
import org.openlca.core.results.UpstreamNode;
import org.openlca.core.results.UpstreamTree;
import org.openlca.util.Strings;

import java.util.ArrayList;
import java.util.List;

public class ImpactTreeExtractor {

    /**
     * 获取所有影响类别的贡献树（完全1:1对应UI结构）
     */
    public static List<ImpactTreeNode> extract(LcaResult result) {
        List<ImpactTreeNode> treeList = new ArrayList<>();
        if (result == null || result.impactIndex() == null)
            return treeList;

        for (ImpactDescriptor impact : result.impactIndex()) {
            // 构建上游树
            var tree = UpstreamTree.of(result.provider(), impact);
            if (tree.root == null)
                continue;

            // 根节点
            ImpactTreeNode rootNode = toNode(tree.root, impact);
            rootNode.setChildren(toChildren(tree, tree.root, impact));
            treeList.add(rootNode);
        }
        return treeList;
    }

    private static List<ImpactTreeNode> toChildren(UpstreamTree tree, UpstreamNode node, ImpactDescriptor impact) {
        List<ImpactTreeNode> children = new ArrayList<>();
        for (UpstreamNode child : tree.childs(node)) {
            ImpactTreeNode n = toNode(child, impact);
            n.setChildren(toChildren(tree, child, impact));
            children.add(n);
        }
        return children;
    }

    private static ImpactTreeNode toNode(UpstreamNode node, ImpactDescriptor impact) {
        ImpactTreeNode dto = new ImpactTreeNode();

        var prov = node.provider();
        if (prov != null && prov.flow() != null) {
            dto.setName(prov.flow().name);
            //dto.setCategory(prov.flow().category != null ? prov.flow().category.name : "");
            //dto.setInventoryUnit(prov.flow().getReferenceUnit());
        } else {
            dto.setName("Unknown");
            dto.setCategory("");
            dto.setInventoryUnit("");
        }

        dto.setInventoryResult(!Double.isNaN(node.requiredAmount()) ? node.requiredAmount() : 0);
        //dto.setImpactFactor(!Double.isNaN(node.impactFactor()) ? node.impactFactor() : 0);
        dto.setImpactFactor(!Double.isNaN(node.scalingFactor()) ? node.scalingFactor() : 0);
        dto.setImpactResult(!Double.isNaN(node.result()) ? node.result() : 0);
        //dto.setImpactUnit(Strings.orElse(impact.referenceUnit, ""));
        dto.setImpactUnit(impact.referenceUnit);

        // 构造影响因子单位（ImpactUnit/InventoryUnit）
        if (Strings.notEmpty(dto.getImpactUnit()) && Strings.notEmpty(dto.getInventoryUnit())) {
            dto.setImpactFactorUnit(dto.getImpactUnit() + "/" + dto.getInventoryUnit());
        } else if (Strings.notEmpty(dto.getInventoryUnit())) {
            dto.setImpactFactorUnit("1/" + dto.getInventoryUnit());
        } else {
            dto.setImpactFactorUnit("");
        }

        return dto;
    }


}